<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 * 用户封禁
 */
class UserForbidden extends Model
{
    protected $table = 'user_forbidden';

    protected $fillable = [
        'user_id', 'forbid_mins', 'flag', 'start_ts', 'end_ts'
    ];

    /**
     * 获取已经解禁的用户
     */
    static function getValidUserIds()
    {
        $where = [
            ['end_ts', '<=', time()],
            ['flag', 1]
        ];
        return self::where($where)->pluck('user_id')->toArray();
    }

    /**
     * 更新已经解禁的记录状态
     */
    static function updateLogStatus()
    {
        $where = [
            ['end_ts', '<=', time()],
            ['flag', 1]
        ];
        return self::where($where)->update(['flag' => 0]);
    }

    /**
     * 封禁用户
     */
    static function doForbidden($userId = 0, $mins = 1, $start = 0)
    {
        if (!$userId) return false;
        //之前记录失效
        self::cancelForbidden($userId);
        //插入新记录
        $info = [
            'user_id' => $userId,
            'forbid_mins' => $mins,
            'flag' => 1
        ];
        if ($start) $info['start_ts'] = $start;
        else $info['start_ts'] = time();
        $info['end_ts'] = $info['start_ts'] + $mins * 60;
        return self::create($info);
    }

    /**
     * 接触禁言
     */
    static function cancelForbidden($userId = 0)
    {
        if (!$userId) return false;
        return self::where('user_id', $userId)->update(['flag' => 0]);
    }
}
